package com.sumbo.config.writer;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.sumbo.config.constant.RocketMqConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * \* User: MeiZhongHao
 * \* Date: 2019-06-14
 * \* Time: 16:08
 * \* Description:
 * \
 */
public class RocketMqWriter extends Writer {

    public RocketMqWriter() {
    }

    public static RocketMqWriter instance = new RocketMqWriter();

    private Map<String, DefaultMQProducer> producerMap = new HashMap<>();

    public void init(Map<String, Properties> temp) {
        if (temp == null || temp.size() <= 0) {
            return;
        }
        for (String key : temp.keySet()) {
            DefaultMQProducer producer = new DefaultMQProducer(key);
            producer.setNamesrvAddr(temp.get(key).getProperty(RocketMqConstants.namesrvAddr));
            producer.setInstanceName(temp.get(key).getProperty(RocketMqConstants.instanceName));
            producerMap.put(key, producer);
        }
    }

    public DefaultMQProducer getProducer(String client) {
        return producerMap.get(client);
    }

    public boolean containsProducer(String client) {
        return producerMap.containsKey(client);
    }

    public boolean send(RocketMqOutputContext context, String message) {
        String topicsStr = context.getTopic();
        String[] topics = null;
        if (topicsStr == null || (topics = topicsStr.split(",")) == null || topics.length <= 0) {
            return true;
        }
        for (String topic : topics) {
            try {
                send(context.getClient(), topic, context.getTag(), message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public SendResult send(String client, String topic, String tag, String message) throws Exception {
        DefaultMQProducer producer = getProducer(client);
        if (producer == null) {
            throw new Exception(" No producer named " + client);
        }
        Message msg = new Message();
        msg.setTags(tag);
        msg.setTopic(topic);
        msg.setBody(message.getBytes());
        SendResult sendResult = producer.send(msg);
        return sendResult;
    }
}